#include "DeviceHandler.h"
#include <sstream>

void DeviceHandler::open()
{
	status_ = FT_Open(device_, &handle_);

	if(FT_OK != status_)
	{
		throw std::exception("error occured while opening device: " + device_);
	}
}

void DeviceHandler::close()
{
	FT_Close(handle_);
}

FT_STATUS DeviceHandler::get_status()
{
	return status_;
}

FT_HANDLE DeviceHandler::get_handle()
{
	return handle_;
}

std::string DeviceHandler::get_details()
{
	std::stringstream result;
	DWORD num_devs; 
	DWORD flags; 
	DWORD ID; 
	DWORD type; 
	DWORD loc_ID; 
	char serial_number[16]; 
	char description[64];

	status_ = FT_CreateDeviceInfoList(&num_devs); 

	if (FT_OK == status_) 
	{
		result << "Number of devices: " << num_devs << std::endl;
	}

	if (num_devs > 0) 
	{
		status_ = FT_GetDeviceInfoDetail(device_, &flags, &type, &ID, &loc_ID, serial_number, description, &handle_); 

		if (FT_OK == status_)
		{
			result << "Device " << device_	<< ':'				<< std::endl;
			result << "- Flags: "			<< flags			<< std::endl; 
			result << "- Type: "			<< type				<< std::endl;
			result << "- ID: "				<< ID				<< std::endl; 
			result << "- LocId: "			<< loc_ID			<< std::endl; 
			result << "- SerialNumber: "	<< serial_number	<< std::endl;
			result << "- Description: "		<< description		<< std::endl; 
			result << "- Handle: "			<< handle_			<< std::endl;
		}
	}
	return result.str();
}

DWORD DeviceHandler::write(char *bytes, size_t size)
{
	DWORD written_;
	status_ = FT_Write(handle_, bytes, size, &written_);

	if (FT_OK != status_) 
	{
		throw std::exception("tx error occured");
	}
	return written_;
}

DWORD DeviceHandler::read(char *bytes, size_t size)
{
	DWORD received_;
	status_ = FT_Read(handle_, bytes, size, &received_);

	if (FT_OK != status_) 
	{
		throw std::exception("rx error occured");
	}
	return received_;
}